<template>
  <div class="student_card_batch_recharge">
    <el-form :inline="true" :model="elform" class="demo-form-inline" size="mini">
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-download"
          @click="thetemplate()"
        >execl模板下载</el-button>
      </el-form-item>
      <el-form-item style="paddingLeft:20px">
        <div class="bulk_import">
          <el-upload
            class="upload-demo"
            action
            :on-change="handleChange"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :file-list="fileListUpload"
            :limit="limitUpload"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :auto-upload="false"
          >
            <el-button type="primary" @click="handleclickto()" icon="el-icon-upload2">导入</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="rechargebulk(rechargeChecked)">批量充值</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="exportexecl()">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-if="table1"
      :data="studentlist"
      :stripe="true"
      style="width:100%"
      border="border"
      key="table1"
      :header-cell-style="headFirst"
      highlight-current-row
      @selection-change="handleSelectionChange"
      :show-overflow-tooltip="true"
      v-loading="importLoad"
      height="calc(100vh - 220px)"
      ref="importTable"
      :cell-style="(res) => headFirst_col(res, [])"
    >
      <el-table-column label="是否选中" prop="isCheck" align="center" width="55">
        <template slot="header" slot-scope="scope">
          <el-checkbox :value="isSelectAll" @change="CheckSelectAll" :disabled="isError" />
        </template>
        <template slot-scope="scope">
          <el-checkbox
            :value="scope.row.isCheck"
            @change="(isCheck) =>CheckSelect(isCheck,scope.row)"
            :disabled="isError"
          />
        </template>
      </el-table-column>
      <el-table-column prop="messageError" label="充值失败原因" v-if="isError"></el-table-column>
      <el-table-column prop="cardNumber" label="卡号"></el-table-column>
      <el-table-column prop="userName" label="名字"></el-table-column>
      <el-table-column prop="moneyAmount" label="金额(元)"></el-table-column>
    </el-table>
    <!-- <el-table
      v-if="table2"
      id="out-table"
      :data="studentlist"
      :stripe="true"
      style="width:100%"
      border="border"
      key="table2"
      :header-cell-style="headFirst"
    >
    
      <el-table-column prop="userName" label="学生姓名"></el-table-column>
      <el-table-column prop="cardNumber" label="卡号"></el-table-column>
      <el-table-column prop="moneyAmount" label="金额(元)"></el-table-column>
      <el-table-column prop="messageError" label="充值结果"></el-table-column>
    </el-table>-->
    <div class="page">
      <el-pagination
        @size-change="handleSizeChangeY"
        @current-change="handleCurrentChangepageY"
        :current-page="pageY"
        :page-sizes="[20,40, 80,120]"
        :page-size="pageSizeY"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalY"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      elform: {},
      messageType: 0,
      studentlist: [],
      agentGuid: "",
      identity: "",
      amountvalue: "",
      fileListUpload: [],
      limitUpload: 1,
      rechargeChecked: [],
      table1: true,
      table2: false,
      studentlist: [],
      schooloptions: [],
      schoolid: "",
      schoolidchange: true,
      filename: "学卡批量充值结果",
      // 导入表格等待
      importLoad: false,
      // 错误信息显示
      isError: false,
      // 是否全选
      isSelectAll: false,
      // 分页变量
      changestudentY: [],
      // 原始页数
      pageY: 1,
      // 每条个数
      pageSizeY: 20,
      // 总条数
      totalY: 0,
    };
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      },
    },
  },
  methods: {
    thetemplate() {
      this.$http({
        url: this.$http.adornUrl("/voip/user/POIUserRechargeDownload"),
        method: "post",
        data: this.$http.adornData({}),
        responseType: "blob",
      }).then(({ data }) => {
        this.downloadFile(data);
      });
    },
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return;
      }
      const nowtime = this.getimeto();
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "批量充值模板" + nowtime + ".xlsx");
      document.body.appendChild(link);
      link.click();
    },
    handleSelectionChange(val) {
      this.rechargeChecked = val;
    },
    handleChange(file, fileList) {
      this.initList();
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.studentlist = [];
          this.table1 = true;
          this.table2 = false;
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    handleExceed(file, fileList) {
      this.initList();

      fileList[0].name = file[0].name;
      this.fileTemps = file[0];
      if (this.fileTemps) {
        this.studentlist = [];
        this.table1 = true;
        this.table2 = false;
        if (
          this.fileTemps.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemps.type == "application/vnd.ms-excel"
        ) {
          this.importfxx(this.fileTemps);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    handleRemove(file, fileList) {
      this.initList();

      this.studentlist = [];
      this.fileTemp = null;
    },
    handleclickto() {},
    // 批量充值
    rechargebulk() {
      if(this.importLoad){
        this.$message({
          showClose: true,
          message: "正在批量充值请勿重复操作",
          type: "warning",
          duration:"500"
        });
        return false;
      }
      let rechargeCheckedto = this.getData();
      if (rechargeCheckedto.length == 0) {
        this.$message({
          showClose: true,
          message: "没有充值数据",
          type: "warning",
        });
        return false;
      } else {
        for (var i = 0; i < rechargeCheckedto.length; i++) {
          rechargeCheckedto[i].unitGuid = this.changeschoolid;
          rechargeCheckedto[i].cardNumber = String(
            rechargeCheckedto[i].cardNumber
          );
          rechargeCheckedto[i].moneyAmount = String(
            rechargeCheckedto[i].moneyAmount
          );
        }
        this.importLoad = true;
        this.$http({
          url: this.$http.adornUrl("/user/recharge/detail/getJsonUserRecharge"),
          method: "post",
          data: this.$http.adornData({
            messageContent: rechargeCheckedto,
            messageType: this.messageType,
          }),
        }).then(({ data }) => {
          this.importLoad = false;
          this.initList();
          if (data.messageCode == 200) {
            if (data.messageContent.errorList) {
              this.changestudentY = data.messageContent.errorList;
              this.totalY = this.changestudentY.length;
              this.getUserList(this.pageY, this.pageSizeY);
              this.isError = true;
              this.$message({
                message: data.messageContent.errorStr,
                type: "warning",
              });
              this.$nextTick(() => {
                this.$refs["importTable"].doLayout();
              });
            } else {
              this.$message({
                message: "批量充值完成",
                type: "success",
              });
            }
            // console.log(data);
            // this.table1 = false;
            // this.table2 = true;
            // let arr = data.messageContent;
            // for (var i = 0; i < arr.length; i++) {
            //   if (arr[i].messageError == "") {
            //     arr[i].messageError = "充值成功";
            //   }
            // }
            // this.studentlist = arr;
            // this.rechargeChecked = [];
            // this.$message({
            //   message: "批量充值完成",
            //   type: "success",
            // });
          } else {
            this.$message({
              message: "批量充值失败",
              type: "error",
            });
          }
        });
      }
    },
    exportexecl() {
      if (this.studentlist.length != 0 && this.studentlist[0].messageError) {
        this.export2Excel();
      } else {
        this.$message({
          message: "请批量充值后再导出",
          type: "warning",
        });
        return false;
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    export2Excel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        const multiHeader = [];
        const multiHeader2 = [];
        const merges = [];
        const { export_json_to_excel } = require("../../../excel/Export2Excel");
        const tHeader = ["学生姓名", "卡号", "金额(元)", "充值结果"];
        const filterVal = [
          "userName",
          "cardNumber",
          "moneyAmount",
          "messageError",
        ];
        const list = this.changestudentY;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },
    /**
     * 导入相关函数
     */
    // 数据初始化
    initList() {
      // 关闭加载
      this.importLoad = false;
      // 渲染表格初始化
      this.studentlist = [];
      // 表格中拿出的原始数据
      this.changestudentY = [];
      // 原始页数
      this.pageY = 1;
      // 每条个数
      this.pageSizeY = 20;
      // 总条数
      this.totalY = 0;
      // 原始的显示数据数
      this.showPageSizeY = 20;
      this.isSelectAll = false;
      this.isError = false;
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.studentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      );
    },
    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val;
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val;
      this.changestudentY.map((item) => {
        item.isCheck = val;
      });
    },
    // 导入数据处理
    getData() {
      let arr = [];
      this.changestudentY.map((item) => {
        if (item.isCheck) {
          arr.push(item);
        }
      });
      return arr;
    },
    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },
    handleCurrentChangepageY(val) {
      this.pageY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },
    //导入函数
    importfxx(obj) {
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((v) => {
            let obj = {};
            obj.cardNumber = v["卡号"];
            obj.userName = v["名字"];
            obj.moneyAmount = v["金额（元）"];
            arr.push(obj);
          });
          console.log(arr);
          arr.map((item, index) => {
            item.isCheck = _this.isSelectAll;
            item.id = index;
          });
          _this.changestudentY = arr;
          _this.totalY = arr.length;
          _this.getUserList(_this.pageY, _this.pageSizeY);
          //   _this.studentlist = [...arr];
        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.student_card_batch_recharge {

  padding: 10px;
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    /deep/.el-form-item__label {
      padding-right: 5px;
    }
    .el-form-item {
      margin-bottom: 5px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 250px;
    }
  }
  .bulk_import {
    padding-left: 20px;
    .upload-demo {
      display: flex;
      align-items: center;
      /deep/.el-upload-list {
        //  margin-left: 60px;
      }
      /deep/.el-upload-list__item-name {
        margin-right: 22px;
      }
    }
  }
    .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>